package com.jming.jike.service.front.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jming.jike.common.BusinessException;
import com.jming.jike.config.MybatisPlusConfig;
import com.jming.jike.dto.front.UserDTO;
import com.jming.jike.dto.front.UserLoginDTO;
import com.jming.jike.entity.User;
import com.jming.jike.mapper.UserMapper;
import com.jming.jike.service.front.UserService;
import com.jming.jike.util.CommonUtils;
import com.jming.jike.util.CopyBeanUtils;
import com.jming.jike.util.RedisUtil;
import com.jming.jike.util.ValidateCodeUtils;
import com.jming.jike.vo.front.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 用户信息(User)表服务实现类
 *
 * @author makejava
 * @since 2022-04-16 02:02:52
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CommonUtils commonUtils;

    @Resource
    private MybatisPlusConfig mybatisPlusConfig;

    private final String key = "getCode_";

    @Override
    public Boolean getCode(UserLoginDTO userLoginDTO) {

        // 查询缓存是否存在验证码
        String phone = userLoginDTO.getPhone();
        // 缓存key
        String phoneKey = key + phone;
        if (StringUtils.hasText(redisUtil.getKeyWillThrow(phoneKey))) {

            throw new BusinessException("验证码已发送, 请勿重复发送!");
        }

        // 将验证码添加至缓存
        String code = ValidateCodeUtils.generateValidateCode(5).toString();
        log.info("生成验证码, 手机号 {} 验证码 {}", phone, code);
        if (!redisUtil.setIfAbsentWillThrow(phoneKey, code, 5)) {

            throw new BusinessException("发送验证码失败!");
        }

        // 向手机号发送验证码 TODO

        // 发送失败删除缓存中的验证码
//        if (redisUtil.getDelete(phone)) {
//
//           throw new BusinessException("发送验证码失败!");
//        }

        return true;
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {

        // 获取验证码
        String phone = userLoginDTO.getPhone();
        // 缓存key
        String phoneKey = key + phone;
        String code = redisUtil.getKeyWillThrow(phoneKey);
        log.info("获取验证码 入参 {} 验证码 {}", JSON.toJSONString(userLoginDTO), code);

        if (!StringUtils.hasText(code)) {
            throw new BusinessException("验证码已过期!");
        }

        if (!code.equals(userLoginDTO.getCode())) {
            throw new BusinessException("验证码不正确!");
        }

        // 根据手机号查询用户信息
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getPhone, phone).last("limit 1"));

        //判断当前手机号对应的用户是否为新用户, 如果是新用户就自动完成注册
        if (user == null) {
            user = User.builder()
                    // 名称 默认手机号后4位
                    .name(phone.substring(phone.length() - 4))
                    .phone(phone)
                    .status(1).build();

            userMapper.insert(user);
        }

        // 删除缓存的验证码
        redisUtil.getDelete(phoneKey);
        return user;
    }

    @Override
    public UserVO getUserInfo() {

        return CopyBeanUtils.copyBean(userMapper.selectById(mybatisPlusConfig.getOperId()), new UserVO());
    }

    @Override
    public Boolean updateUserInfo(UserDTO userDTO) {

        // 手机号
        String phone = userDTO.getPhone();
        // 用户id
        Long operId = mybatisPlusConfig.getOperId();

        // 用户信息
        User dbUser = userMapper.selectById(operId);

        // 如果手机号不相等  则说明修改了手机号 需要验证码
        if (StringUtils.hasText(phone) && !dbUser.getPhone().equals(phone)) {
            if (!StringUtils.hasText(userDTO.getCode())) {

                throw new BusinessException("请输入验证码");
            }

            // 获取验证码
            String code = redisUtil.getKeyWillThrow(key + phone);
            log.info("UserServiceImpl updateUserInfo 获取验证码 手机号 {} 验证码 {}", phone, code);
            if (!userDTO.getCode().equals(code)) {

                throw new BusinessException("验证码不正确!");
            }

            // 删除缓存中的验证码
            redisUtil.getDelete(key + phone);
        }

        // 修改用户信息
        User user = CopyBeanUtils.copyBean(userDTO, new User());
        user.setId(dbUser.getId());
        if (userMapper.updateById(user) < 0) {

            throw new BusinessException("信息修改失败, 请稍后再试!");
        }

        // 如果原来的头像跟现在的头像信息不一致 删除原来的头像
        if (StringUtils.hasText(dbUser.getAvatar()) && dbUser.getAvatar().equals(userDTO.getAvatar())) {
            commonUtils.removeImage(dbUser.getAvatar(), userDTO.getAvatar());
        }

        return true;
    }
}
